import json
import os.path
import xml.etree.ElementTree as ET

import pandas as pd
import requests


def convert_url(url):
    if not isinstance(url, str):
        return None
    # 如果url以.json结尾，直接返回
    if url.endswith('.json'):
        return url
    # 判断是否是https://issues.apache.org
    if not url.startswith("https://issues.apache.org"):
        return None
    issue_key = url.split('/')[-1]  # 获取 URL 中最后的部分，例如 "CLI-13"
    # 构建 XML URL
    return f"https://issues.apache.org/jira/si/jira.issueviews:issue-xml/{issue_key}/{issue_key}.xml"


class Download:
    def __init__(self, file_path, file_name):
        self.path = file_path
        self.data = pd.read_csv(os.path.join(str(file_path), file_name))
        self.urls = self.data['report.url'].apply(convert_url).tolist()

        # print(os.path.join(str(file_path), file_name))

    def download_defect_report(self):
        """下载缺陷报告"""
        res = []
        for url in self.urls:
            if url is None:
                continue
            response = requests.get(url)

            # 检查请求是否成功
            if response.status_code == 200:
                # 加载 XML 数据
                root = ET.fromstring(response.content, parser=ET.XMLParser(encoding='utf-8'))

                res.append(url)

                if root is None:
                    continue

                # 存储结果
                results = []

                # 找到所有 item 节点
                for item in root.findall(".//item"):
                    data = {
                        "title": item.find("title").text if item.find("title") is not None else None,
                        "description": item.find("description").text if item.find("description") is not None else None,
                        "summary": item.find("summary").text if item.find("summary") is not None else None,
                        "comments": []
                    }

                    # 提取 comments 节点内容
                    comments = item.find("comments")
                    if comments is not None:
                        for comment in comments.findall("comment"):
                            comment_text = comment.text if comment.text else ""
                            comment_author = comment.get("author", "Unknown")
                            comment_date = comment.get("created", "Unknown")
                            data["comments"].append({
                                "author": comment_author,
                                "created": comment_date,
                                "text": comment_text
                            })

                    results.append(data)

                save_path = os.path.join(self.path, f"{url.split('/')[-1]}.json")

                # 保存到 JSON 文件
                with open(save_path, "w", encoding="utf-8") as f:
                    json.dump(results, f, indent=4, ensure_ascii=False)
                print(f"提取完成，已保存到:", save_path)
            else:
                print(f"无法下载文件，HTTP状态码: {response.status_code}")
        return res


def download_report_by_csv(file_path, file_name):
    download = Download(file_path, file_name)
    return download.download_defect_report()
